<template>
    <van-nav-bar title="充值" left-arrow @click-left="onClickLeft" :fixed="true" />
    <div class="vannavbar"></div>
    <div class="withdrawal">
        <div class="withdrawal_form">
            <div class="balance" style="margin-bottom: 5px;">
                <p style="text-align: left;
                line-height: 30px;"> <span style="color: #999;"> 系统收款银行： </span>{{ SystemZH.OBackName }} </p>
                <p style="text-align: left;
                line-height: 30px;"> <span style="color: #999;"> 系统收款账号： </span>{{ SystemZH.OAccount }} </p>
                <p style="text-align: left;
                line-height: 30px;"> <span style="color: #999;"> 系统收款户名： </span>{{ SystemZH.OBackUserName }} </p>
                <p style="text-align: left;
                line-height: 30px;"> <span style="color: #999;"> 系统收款支行： </span>{{ SystemZH.OpeningBranch }} </p>
            </div>
            <div class="form_submit" style="padding-top: 5%;">
                <van-field name="Amount" label="本次充值金额" input-align="right" type="number" placeholder="请输入充值金额"
                    v-model="Amount" />
                <van-field name="PayBackName" label="付款银行" label-width="120" input-align="right" placeholder="请输入收款银行"
                    v-model="PayBackName" />
                <van-field name="PayAccount" label="付款账号" label-width="120" input-align="right" placeholder="请输入收款账号"
                    v-model="PayAccount" />
                <van-field name="PayName" label="付款户名" label-width="120" input-align="right" placeholder="请输入收款户名"
                    v-model="PayName" />
                <van-field name="uploader" label-width="120" input-align="right" label="上传支付凭证:">
                    <template #input>
                        <van-uploader result-type="file" max-count="1" :deletable="!detail" v-model="uploader"
                            :before-read="beforeRead" :after-read="afterRead" :before-delete="delImg" />
                    </template>
                </van-field>
            </div>
            <div class="form_btn">
                <van-button block type="primary" native-type="submit" class="btn1" @click="AddCashOrderSubmit()"> 充值
                </van-button>
            </div>
        </div>
        <van-list v-model="loading" :finished="finished" :finished-text="CashOrderList.length > 0 ? '已经到底了哦' : ''"
            @load="onLoad">
            <div class="withdrawal_list">
                <div class="titel"> 充值记录 </div>
                <div class="list" v-if="CashOrderList.length > 0">
                    <div class="int" :key="index" v-for="(Item, index) in CashOrderList">
                        <div class="with_a">
                            <div class="lf"> 充值时间：{{ Item.CreateTime }} </div>
                            <div class="rt"> {{ filters(Item.State) }}</div>
                        </div>
                        <div class="with_a">
                            <div class="lf"> 充值金额：{{ Item.Amount }}元 </div>
                        </div>
                    </div>
                </div>
                <div class="vanEmpty" v-else>
                    <van-empty image-size="100px" description="暂无数据" />
                </div>
            </div>
        </van-list>
    </div>
</template>

<script>
import { onMounted, reactive, ref, toRefs } from 'vue'
import { Toast, Notify } from 'vant';
import { Dialog } from 'vant';
import { useStore } from "vuex"; // ⚪️ 引入状态管理
import { useRoute, useRouter } from "vue-router";
import router from "@/router";
import { GetRechargeList, AddRecharge, GetSystemZH, UploadFile } from "@/network/recharge";

export default {
    setup() {
        const store = useStore(); // 获取对象
        const state = reactive({
            token: store.state.user.token,
            CashOrderList: [],
            SystemZH: {},
            Security: '',//安全密码
            Amount: 0,//  充值积分
            AmountType: 1,//1 解冻积分 2 团队积分 ,
            PayAccount: '',//支付账号
            PayBackName: '',// 支付银行
            PayName: '',// 支付户名

            RealName: '',
            Remark: '',
            loading: false,
            finished: false,
            pageSize: 5,
            currentPage: 1,
            Total: 0,
            //图片上传
            flag: false, // 上传时候禁用上传按钮
            PayImg: '',
            uploader: [], // 组件默认显示图片信息

        });
        onMounted(() => {
            init();
            getUser();
        });

        //充值
        const AddCashOrderSubmit = () => {
            if (state.Amount < 0 || state.Amount == 0) {
                Notify({ type: 'warning', message: '充值金额必须大于0' });
                return false
            }
            if (!state.PayImg) {
                Notify({ type: 'warning', message: '请上传支付凭证' });
                return false
            }
            if (!state.PayBackName) {
                Notify({ type: 'warning', message: '请输入付款银行名称' });
                return false
            }
            const toast = Toast.loading({
                duration: 0,
                forbidClick: true,
                message: '正在充值中...',
            });
            var params = {
                MemberId: state.token.ID,
                Amount: state.Amount,
                PayBackName: state.PayBackName,
                PayAccount: state.PayAccount,
                PayName: state.PayName,
                OBackName: state.SystemZH.OBackName,
                OAccount: state.SystemZH.OAccount,
                OBackUserName: state.SystemZH.OBackUserName,
                OpeningBranch: state.SystemZH.OpeningBranch,
                PayImg: state.PayImg,
                Remark: '充值',
            }
            AddRecharge(params).then((res) => {
                if (res.Code == 0) {
                    init();
                    Dialog.alert({
                        title: '提示',
                        message: '充值成功，请注意账号到账情况！',
                        confirmButtonColor: '#73D56C',
                        theme: 'round-button',
                    }).then(() => { });
                } else {
                    Dialog.alert({
                        title: '提示',
                        confirmButtonColor: '#E46E6E',
                        message: res.Message + '！',
                        theme: 'round-button',
                    }).then(() => { });
                }
                getUser();
                state.Amount = 0;
                toast.clear()
            });
        };
        // 上传图片前返回布尔值
        const beforeRead = (file) => {
            if (
                file.type !== "image/png" &&
                file.type !== "image/jpeg" &&
                file.type !== "image/jpg"
            ) {
                this.$toast.fail("请上传 png,jpg格式图片");
                return false;
            }
            return true;
        }
        const afterRead = (file) => {
            state.flag = true;
            file.status = "uploading";
            file.message = "上传中...";
            let formData = new FormData(); // 上传图片要formData类型
            formData.append("uploadImage", file.file);
            UploadFile(formData).then((response) => {
                if (response.Code == 0) {
                    file.status = "done";
                    file.message = "上传完成";
                    state.flag = false;
                    state.PayImg = response.Data; // 因为只有一张，直接传1个字符串
                } else {
                    file.status = "failed";
                    file.message = "上传失败";
                }
            });
        }
        //删除图片
        const delImg = (file, detail) => {
            state.PayImg = ''; // 只有一张直接清空数组
            return true
        }
        const onLoad = () => {
            if (state.CashOrderList.length == state.Total) {
                if (state.CashOrderList.length != 0) {
                    state.loading = false
                    state.finished = true
                }
            } else {
                state.currentPage = parseInt(state.currentPage) + 1;
                init();
            }
        }
        // 初始化信息
        const init = () => {
            var params = {
                memberId: state.token.ID,
                pageSize: state.pageSize,
                currentPage: state.currentPage
            }
            GetRechargeList(params).then((res) => {
                if (res.Code == 0) {
                    var data = res.Data;
                    state.Total = res.Pager.Total
                    if (data.length > 0) {
                        data.forEach(element => {
                            state.CashOrderList.push(element)
                        });
                    } else {
                        state.finished = true
                    }
                } else { }
            });
            GetSystemZH({ memberId: state.token.ID }).then((res) => {
                if (res.Code == 0) {
                    var data = res.Data;
                    state.SystemZH = data
                    console.log(res);
                } else { }
            });
        };
        //获取用户信息 更新余额
        const getUser = () => {
            store.dispatch("GetMemberInfo", { Id: store.state.user.token.ID }).then((res) => {
                state.token = res.Data;
                state.PayBackName = state.token.OBackName;
                state.PayAccount = state.token.OAccount || '';
                state.PayName = state.token.OBackUserName || '';

            }).catch(() => { });
        }
        //过滤器
        function filters(id) {
            let txt = "";
            switch (id) {
                case 1:
                    txt = "待审核";
                    break;
                case 2:
                    txt = "审核失败";
                    break;
                case 4:
                    txt = "审核成功";
                    break;
                case 8:
                    txt = "充值完成";
                    break;
                case -1:
                    txt = "充值失败";
                    break;
            }
            return txt;
        }
        const onClickLeft = () => {
            router.push({ path: "/pointscenter" });
        };
        return {
            ...toRefs(state),
            onClickLeft,
            AddCashOrderSubmit,
            filters,
            onLoad,
            afterRead,
            delImg,
            beforeRead
        };
    },
};
</script>

<style scoped></style>